package com.xin.libandroidpaysocial.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xin.libandroidpaysocial.share.Constant;
import com.xin.libandroidpaysocial.share.QQUserInfo2;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by user on 2017/11/15.
 * 功能描述：第三方平台 登录
 */

public class LoginUtils {

    public static LoadSuccessListener getListener() {
        return listener;
    }

    public static class LoadSuccessListener {
        public void onWx(String code) {
        }

        public boolean onWxFail(String code) {
            return false;
        }

        public void onQQ(String id, String nickname, String openId) {

        }

        public void onWB(String id, String nickname, String openId) {

        }
    }

    private static LoadSuccessListener listener;

    public static LoadSuccessListener setListener(LoadSuccessListener listener) {
        return LoginUtils.listener = listener;
    }

    /**
     * 微信登录 WXEntryActivity类
     *
     * @param context
     */
    public static void wx(Activity context) {
        final IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.WX_AppID);
        api.registerApp(Constant.WX_AppID);
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context, "未安装微信客户端", Toast.LENGTH_SHORT).show();
        } else {
            wxLoginByApp(context, api);
        }
    }


    /**
     * @param context
     * @param api
     */
    private static void wxLoginByApp(Context context, IWXAPI api) {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
    }

    /**
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public static void onActivityResult(int requestCode, int resultCode, Intent data) {

        Tencent.onActivityResultData(requestCode, resultCode, data, new IUiListener() {
            @Override
            public void onComplete(Object o) {
                log("onComplete() called with: o = [" + o + "]");
            }

            @Override
            public void onError(UiError uiError) {
                log("onError() called with: uiError = [" + uiError + "]");
            }

            @Override
            public void onCancel() {
                log("onCancel() called");
            }
        });
    }

    /**
     * qq登录
     * 在调用的activity中 onActivityResult
     *
     * @param context
     */

    public static void qq(final Activity context) {
        final Tencent mTencent = Tencent.createInstance(Constant.QQ_AppID, context.getApplicationContext());
        if (mTencent.isSessionValid()) {
            qqUserInfo(context);
            return;
        }
        mTencent.login(context, "get_user_info,add_topic", new IUiListener() {

            @Override
            public void onComplete(Object o) {
                log("onComplete() called with: o = [" + o + "]");
                if (o instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) o;
                    try {
                        if (jsonObject.getInt("ret") == 0) {
                            String openId = jsonObject.getString("openid");
                            String access_token = jsonObject.getString("access_token");
                            String expires_in = jsonObject.getString("expires_in");
                            mTencent.setOpenId(openId);
                            mTencent.setAccessToken(access_token, expires_in);
                            /*查用户信息*/
                            qqUserInfo(context);
                            return;

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Toast.makeText(context, "qq登录出错", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(UiError e) {
                log("onError:" + "code:" + e.errorCode + ", msg:"
                        + e.errorMessage + ", detail:" + e.errorDetail);
                Toast.makeText(context, "qq登录出错", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                log("onCancel");
                Toast.makeText(context, "qq登录取消", Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 获得qq个人信息
     *
     * @param context
     */
    private static void qqUserInfo(final Activity context) {
        final Tencent mTencent = Tencent.createInstance(Constant.QQ_AppID, context.getApplicationContext());
        QQUserInfo2 userInfo = new QQUserInfo2(context, mTencent.getQQToken());
        userInfo.getUserInfo(new IUiListener() {
            @Override
            public void onComplete(Object o) {
                if (o instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) o;
                    if (listener != null) {
                        String nickname = null;
                        String figureurl = null;
                        try {
                            /*有用户未授权的情况*/
                            nickname = jsonObject.getString("nickname");
                            figureurl = jsonObject.getString("figureurl_qq_1");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        listener.onQQ(mTencent.getOpenId(), nickname,
                                figureurl);
                        return;
                    }
                }
                Toast.makeText(context, "qq登录出错", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(UiError uiError) {
                log("onError() called with: uiError = [" + uiError + "]");
                Toast.makeText(context, "qq登录出错", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                log("onCancel() called");
                Toast.makeText(context, "qq登录已取消", Toast.LENGTH_SHORT).show();
            }

        });
    }

    /**
     * 微博登录
     * 在调用的activity中 onActivityResult
     *
     * @param context
     */
    public static void wb(final Activity context) {/*
        AuthInfo mAuthInfo = new AuthInfo(context, Constant.WB_APP_KEY, Constant.WB_REDIRECT_URL, Constant.WB_SCOPE);
        WbSdk.install(context, mAuthInfo);
        mSsoHandler = new SsoHandler(context,mAuthInfo);
        mSsoHandler.authorize(new WbAuthListener() {
            @Override
            public void onSuccess(final Oauth2AccessToken values) {
                log("onSuccess() called with: values = [" + values + "]");
                WeiboParameters weiboParameters = new WeiboParameters(Constant.WB_APP_KEY);
                weiboParameters.put("access_token", values.getToken());
                weiboParameters.put("uid", values.getUid());
                *//*获取用户信息*//*
                NetUtils.internalHttpRequest(context, "https://api.weibo.com/2/users/show.json",
                        weiboParameters, "GET",
                        new RequestListener() {
                            @Override
                            public void onComplete(String s) {
                                log("onComplete() called with: s = [" + s + "]");
                                String nickName = "", avatar = "";
                                try {
                                    JSONObject jsonObject = new JSONObject(s);
                                    nickName = jsonObject.getString("screen_name");
                                    avatar = jsonObject.getString("profile_image_url");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                if (listener != null) {
                                    listener.onWB(values.getUid(), nickName, avatar);
                                }
                            }

                            @Override
                            public void onWeiboException(WeiboException e) {
                                log("onWeiboException() called with: e = [" + e + "]");
                            }
                        });
            }

            @Override
            public void cancel() {
                log("cancel() called");
                Toast.makeText(context, "微博登录已取消", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {
                log("onFailure() called with: wbConnectErrorMessage = [" + wbConnectErrorMessage + "]");
                Toast.makeText(context, "微博登录失败", Toast.LENGTH_SHORT).show();
            }
        });
    */}


    private static void log(String s) {
        Log.e(LoginUtils.class.getSimpleName(), s);
    }
}


